<!DOCTYPE html>
<html lang="zh">

<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">
	<title>Canvas连线</title>
	<style media="screen">
		* {
			margin: 0;
			padding: 0;
		}

		#wrap {
			width: 100%;
			background: #000;
		}

		#canvas {
			display: block;
		}
	</style>
</head>

<body>
	<div id="wrap">
		<canvas id="canvas"></canvas>
	</div>

	<script type="text/javascript">
		// 获取窗口宽高
		var h = window.innerHeight,
			w = window.innerWidth;
		document.getElementById('wrap').style.height = h + 'px';

		var con = document.getElementById('canvas');
		// 设置画布
		var c = con.getContext('2d');
		// 给画布设置宽高，此处必须是setAttribute，设置style会导致画出来的图像变形
		con.setAttribute('width', w);
		con.setAttribute('height', h);
		// 监听窗口resize事件，动态设置宽高
		window.onresize = function () {
			h = window.innerHeight;
			w = window.innerWidth;
			document.getElementById('wrap').style.height = h + 'px';
			con.setAttribute('width', w);
			con.setAttribute('height', h);
		}

		// 创建一个圆点对象
		function dot() {
			this.x = Math.random() * w; // X轴坐标，0 - w
			this.y = Math.random() * h; // Y轴坐标， 0 - y
			this.r = Math.random() * 2 + 2; // 圆点半径， 5 - 10
		}

		// 圆点合集
		var dots = [];
		for (var i = 0; i < 1000; i++) {
			dots.push(new dot());
		}

		con.onmousemove = function (e) {
			c.clearRect(0,0,w,h);
			for (var j = 0; j < dots.length; j++) {
				var d = dots[j];
				var s = Math.sqrt(Math.pow((e.x - d.x), 2) + Math.pow((e.y - d.y), 2) - d.r / 2); //利用勾股定理计算出距离
				// 如果两点之间的距离小于某个值，就将两点进行连线
				if (s != NaN && s < 150) {
					c.beginPath();
					c.moveTo(d.x, d.y); // 线的起点
					c.lineTo(e.x, e.y); // 线的终点
					c.strokeStyle = 'rgba(255,255,255,.3)';
					c.stroke();
				}
			}
		}
	</script>
</body>

</html>
